<template>
  <div class="user-broker-company">
    <van-search
      background="#f2f5f7"
      @input="filterCompany"
      class="search-container"
      placeholder="请输入关键字"
      v-model="keyword"
    >
      <i class="iconfont icon-sousuolan_sousuo" slot="left-icon"></i>
    </van-search>

    <tree-select :data="companyList" @reRender="reRender" />

    <div class="submit-btn" :style="{background:showGuide?'rgba(255, 255, 255, 0)':'#fff'}">
      <van-button
        type="info"
        :disabled="!companyData.id"
        :loading="loading"
        @click="submitHandle"
      >提交审核</van-button>
    </div>
    <div v-if="showGuide" @click="closeGuide" class="guide-company">
      <img :src="require('IMG/user/guide-company-step-2.png')" alt />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import TreeSelect from 'COMP/TreeSelect'
import * as types from '@/store/mutation-types'
import userService from 'SERVICE/userService'
import marketService from 'SERVICE/marketService'

export default {
  data() {
    return {
      keyword: '',
      loading: false,
      companyData: {
        id: null
      },
      companyList: [], //公司数据
      companyTree: [], //公司数据备份
      showGuide: false, //当this.$route.query.guide==2并且clickTimes=1时显示
      clickTimes: 0
    }
  },

  components: {
    TreeSelect
  },

  created() {
    if (this.$route.query.module) {
      document.title = '请选择渠道'
      this.getChannelList()
    } else {
      this.getCompanyList()
    }
    const companyId = this.$route.query.id
    if (companyId) {
      this.companyData.id = companyId
    }
  },

  computed: {
    ...mapGetters(['userInfo'])
  },

  methods: {
    closeGuide() {
      window.localStorage.setItem('company-guide-step2', 0)
      this.showGuide = false
    },

    /** 提交 数据*/
    async submitHandle() {
      this.closeGuide()
      try {
        this.loading = true
        if (this.$route.query.module) {
          let { linkerId, id } = this.companyData
          let rq = { agentId: this.userInfo.agentId, linkerId, newChannelId: id }
          if (this.$route.query.id) rq.oldChannelId = this.$route.query.id
          const channel = await userService.switchChannel(rq)
          await marketService.newOpenLinker({ linkerId, channelId: id })
          this.$toast.success('保存成功')
          setTimeout(() => {
            this.$router.go(-1)
          }, 200)
        } else {
          const response = await userService.upDateUserInfo({ organizationId: this.companyData.id })
          this.$dialog
            .alert({
              message: '您的审核申请已提交成功！24小时内会收到审核结果，请留意消息通知。',
              confirmButtonText: '我知道了'
            })
            .then(() => {
              this.$router.go(-1)
            })
        }
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },

    /** 查询公司树 */
    async getCompanyList() {
      this.$toast.loading({
        mask: true,
        duration: 0,
        message: '加载中...'
      })
      let params = {}
      let uuid = localStorage.getItem('uuid')
      if (uuid) {
        params.configurationUuid = uuid
      }
      const companyList = (await userService.getOrganizationList(params)) || []
      this.$toast.clear()
      this.setSelected(companyList, this.$route.query.id || '')
      this.companyList = companyList
      this.companyTree = companyList
      this.setCompanyLevel(companyList)
    },
    /** 查询渠道列表 */
    async getChannelList() {
      this.$toast.loading({
        mask: true,
        duration: 0,
        message: '加载中...'
      })
      let params = {}
      let uuid = localStorage.getItem('uuid')
      if (uuid) {
        params.uuid = uuid
      }
      const companyList = (await userService.getChannelList(params)) || []
      this.$toast.clear()
      this.setSelected(companyList, this.$route.query.id || '')
      this.companyList = companyList
      this.companyTree = companyList
      if (this.$route.query.id) {
        this.companyData = companyList.find(item => item.id === this.$route.query.id)
      }
      this.setCompanyLevel(companyList)
    },

    /** 更改状态，重新渲染
     * onlyRender- 是否只是重新渲染
     */
    reRender(data, index, onlyRender) {
      const companyList = this.companyList
      if (onlyRender == false) {
        this.setSelected(companyList, data.id)
      }
      this.companyList.splice(0, 0)
      this.companyData = data
      this.clickTimes++
      if (this.clickTimes == 1 && this.$route.query.guide == 1 && window.localStorage.getItem('company-guide-step2') != 0) {
        this.showGuide = true
      }
    },

    /** 重置所有数据的selected为false,或者设置某一项为选中 */
    setSelected(list, id) {
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        item.selected = false
        if (item.id == id) {
          item.selected = true
        }
        if (item.children && item.children.length) {
          this.setSelected(item.children, id)
        }
      }
    },

    /** 设置每级的level标识 */
    setCompanyLevel(companyList) {
      const fn = (list, level, cb) => {
        list.forEach(item => {
          item.level = level
          if (item.children && cb) {
            cb(item.children)
          }
        })
      }

      fn(companyList, 1, list => {
        fn(list, 2, list => {
          fn(list, 3)
        })
      })
    },

    /** filter过滤出数据 */
    matchCompany(data, name) {
      return data.filter(item => item.name && item.name.includes(name))
    },

    /** 过滤公司数据 */
    filterCompany(value) {
      let filterResult = this.matchCompany(this.companyTree, value)
      this.companyList = filterResult.length == 0 ? this.companyTree : filterResult
    }
  }
}
</script>

<style lang="less">
.user-broker-company {
  padding: 0 16px;
  padding-bottom: 80px;
  .search-container {
    // height: 44px;
    padding: 6px 0;
    background: #fff !important;
    .icon-sousuolan_sousuo {
      color: #9ca5b5;
    }
    .van-cell {
      background: #f2f5f7;
    }
    .van-field__body {
      height: 100%;
    }
    .van-field__control {
      height: 100%;
      color: #13284d;
      font-size: 14px;
      font-weight: 400;
    }
  }
  .submit-btn {
    position: fixed;
    height: 76px;
    background: #fff;
    width: 100%;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    z-index: 100;
    .van-button {
      width: 100%;
      margin: 0 auto;
      height: 44px;
      border-radius: 6px;
      color: #fff;
      background: rgba(0, 122, 230, 1);
      border: 0;
      font-size: 16px;
      .van-button__text {
        color: #fff;
      }
    }
    .van-button--disabled {
      background: #c9d5e0;
      color: #ffffff;
      opacity: 1;
    }
  }
  .guide-company {
    position: fixed;
    z-index: 99;
    height: 100vh;
    width: 100vw;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.64);
    img {
      position: fixed;
      bottom: 80px;
      left: 0;
      right: 0;
      margin: 0 auto;
      width: 131px;
      height: 113px;
    }
  }
}
</style>